package com.igame.Controller;

import com.igame.Utils.JwtUtil;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Controller;

@Controller
public class WebSocketController {

    private final SimpMessagingTemplate messagingTemplate;
    private final JwtUtil jwtUtil; // 添加 JwtUtil

    public WebSocketController(SimpMessagingTemplate messagingTemplate, JwtUtil jwtUtil) {
        this.messagingTemplate = messagingTemplate;
        this.jwtUtil = jwtUtil;
    }

    @MessageMapping("/send")
    public void sendMessage(@Payload String message, StompHeaderAccessor headerAccessor) {
        // 从连接头中获取 Authorization
        String token = headerAccessor.getFirstNativeHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 移除 "Bearer " 前缀
        }

        // 从 JWT 中获取用户名
        String username = jwtUtil.getUsernameFromToken(token);
        if (username != null) {
            System.out.println("Received message from " + username + ": " + message);
            messagingTemplate.convertAndSend("/topic/messages", message);
        }
    }
}
